from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QHeaderView, QAbstractItemView, QTableWidgetItem, QMessageBox

from opsql import rootOp


class MPrice():
    def __init__(self):
        self.ui = QUiLoader().load('view/定价管理.ui')
        self.inittable()
        self.ui.searchBtn.clicked.connect(self.inittable)
        self.ui.modifyBtn.clicked.connect(self.modify)
        self.ui.rtShow.setReadOnly(True)
        self.ui.ctShow.setReadOnly(True)
        self.ui.tableWidget.cellClicked.connect(self.cellClicked)

    def cellClicked(self, row):
        self.ui.priceShow.setText(self.ui.tableWidget.item(row, 0).text())
        self.ui.ctShow.setText(self.ui.tableWidget.item(row, 1).text())
        self.ui.rtShow.setText(self.ui.tableWidget.item(row, 2).text())


    def inittable(self):
        ct = self.ui.ctIn.text()
        rt = self.ui.rtIn.text()
        result = rootOp.searchp(ct,rt)
        row = 0
        if result:
            row = len(result)
        self.ui.tableWidget.setRowCount(row)
        self.ui.tableWidget.setColumnCount(3)
        self.ui.tableWidget.setHorizontalHeaderLabels(['定价(元/小时)','电脑类别','机房类型'])
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableWidget.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.ui.tableWidget.verticalHeader().setVisible(False)
        self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)

        for i in range(row):
            for j in range(3):
                data = QTableWidgetItem(str(result[i][j]))
                self.ui.tableWidget.setItem(i, j, data)


    def modify(self):
        row = self.ui.tableWidget.currentRow()
        if row == -1:
            QMessageBox.warning(self.ui, '提示', '请选择')
            return
        onehourprice = int(self.ui.priceShow.text())
        ctname = self.ui.tableWidget.item(row, 1).text()
        rtname = self.ui.tableWidget.item(row, 2).text()
        result = rootOp.modifyp(onehourprice, ctname,rtname)
        if result:
            QMessageBox.information(self.ui, '提示', '修改成功')
            self.inittable()
        else:
            QMessageBox.warning(self.ui, '提示', '修改失败')